// import React, { useState } from 'react';
import React, { useRef, useState, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import VersionConfigForm from '../../components/VersionConfigForm'
import ProTable from '@ant-design/pro-table';
import { message, Upload, Button, Select, Form, Input, InputNumber, Popconfirm, Table, Typography } from 'antd';
import { delOSType, delKernelVersion, getOSTypeList, getKernelVersionList, submitOSType, submitKernelVersion, postChangeKernelVersion } from '../../service';
import { ProForm, ModalForm, ProFormText, ProFormTextArea, ProFormSelect, ProFormSwitch } from '@ant-design/pro-form';
import ProCard from '@ant-design/pro-card';
const { Divider } = ProCard;

const handleDelKernelVersion = async (record, intl) => {
  const hide = message.loading(intl.formatMessage({
    id: 'pages.hotfix.deleting',
    defaultMessage: 'Now deleting'
  }));
  const token = localStorage.getItem('token');
  try {
      let res = await delKernelVersion(record.id, token);
      hide();
      if (res.code == 200) {
          message.success(intl.formatMessage({
            id:'pages.hotfix.delete_success',
            defaultMessage:'Delete Success'
          }));
          getKernelVersionList();
          return true;
      } else {
          message.error(`${intl.formatMessage({id:'pages.hotfix.delete_failed', defaultMessage:'Delete Failed'})}: ${res.message}`);
          return false;
      }
  } catch (error) {
      hide();
      return false;
  }
}

const originData = [];
const VersionConfigList = React.forwardRef((props, ref) => {
  const versionlistRef = useRef();
  const [readonlyone, setReadonlyOne] = useState(false);
  const intl = useIntl();
  const onPostTask = () => {
    versionlistRef.current.reload();
  }
  const KernelConfigChange = (e) => {
    setReadonlyOne(e);
  }

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === 'select' ? 
    <ProFormSelect 
      options={props.OSTypedata === undefined ? [] : props.OSTypedata}
      name="os_type" /> : 
      inputType === 'switch' ? 
      <ProFormSwitch
        style={{
            marginBlockEnd: 16,
        }}
        name="use_src_package"
        initialValue={readonlyone}
        checked={readonlyone}
        checkedChildren={intl.formatMessage({
            id:'pages.hotfix.yes',
            defaultMessage:'Yes'
        })}
        unCheckedChildren={intl.formatMessage({
            id: 'pages.hotfix.no',
            defaultMessage: 'No'
        })}
        onChange={KernelConfigChange}
      /> :
    <ProFormText />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                    id: 'pages.hotfix.please_input_data',
                    defaultMessage:'Please input data'
                }),
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState('');
  const isEditing = (record) => record.id === editingKey;
  const edit = (record) => {
    form.setFieldsValue({
      kernel_version: '',
      os_type: '',
      source: '',
      devel_link: '',
      debuginfo_link: '',
      image: '',
      use_src_package: '',
      ...record,
    });
    setEditingKey(record.id);
  };
  const cancel = () => {
    setEditingKey('');
  };
  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      const Poldata = {
        id: key.id,
        os_type: row.os_type,
        kernel_version: row.kernel_version,
        source: row.source,
        devel_link: row.devel_link,
        debuginfo_link: row.debuginfo_link,
        image:row.image,
        use_src_package: row.use_src_package
      }
      postChangeKernelVersion(Poldata).then(res => {
        if(res.code === 200){
          const item = newData[index];
          newData.splice(index, 1, {
            ...item,
            ...row,
          });
          setData(newData);
          setEditingKey('');
          message.success(intl.formatMessage({
            id:'pages.hotfix.submit_success',
            defaultMessage:'Submit success'
          }));
          versionlistRef.current.reload();
        }
      }).catch(err => {
        console.log(err);
      });
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const columns = [
    {
      title: <FormattedMessage id="pages.hotfix.kernel_version" defaultMessage="kernel_version"/>,
      dataIndex: 'kernel_version',
      key: 'kernel_version',
      width: 180,
      ellipsis: true,
      editable: true,
      valueType: 'input',
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.input_full_kernelversion',
        defaultMessage:'Please input the full kernel version include architecture',
    })
    },
    {
      title: <FormattedMessage id="pages.hotfix.os_type" defaultMessage="os_type"/>,
      dataIndex: 'os_type',
      key: 'os_type',
      width: 120,
      editable: true,
      valueType: 'select',
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.select_os_type',
        defaultMessage:'This is the OS Type of this kernel verion. eg. Anolis for 4.19.91-26.an8.x86_64',
    })
    },
    {
      title: <FormattedMessage id="pages.hotfix.kernel_repo_branch" defaultMessage="repo_branch" />,
      dataIndex: 'source',
      valueType: 'input',
      editable: true,
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.repo_branch_tag',
        defaultMessage:'The tag or branch of this kernel version in its code repo',
    })
    },
    {
      title: <FormattedMessage id="pages.hotfix.kernel_devel_location" defaultMessage="devel_location" />,
      dataIndex: 'devel_link',
      valueType: 'input',
      editable: true,
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.devel_downloadlink',
        defaultMessage: 'Please input the download link of the devel- package',
      })
    },
    {
      title: <FormattedMessage id="pages.hotfix.kernel_debuginfo_location" defaultMessage="debuginfo_location" />,
      dataIndex: 'debuginfo_link',
      valueType: 'input',
      editable: true,
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.debuginfo_downloadlink',
        defaultMessage: 'Please input the download link of the debuginfo- package',
      })
    },
    {
      title: <FormattedMessage id="pages.hotfix.image" defaultMessage="Build image" />,
      dataIndex: 'image',
      valueType: 'input',
      editable: true,
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.image',
        defaultMessage: 'Please input the docker image link to build this kernel',
      })
    },
    {
      title: <FormattedMessage id="pages.hotfix.src_pkg_mark" defaultMessage="Using source packages" />,
      dataIndex: 'use_src_package',
      key: 'use_src_package',
      width: 120,
      editable: true,
      valueType: 'switch',
      render: (_, record) => {
        if(record.use_src_package){
            var returnval = intl.formatMessage({id:'pages.hotfix.yes', defaultMessage:'Yes'})
          return returnval
        }else{
            var returnval = intl.formatMessage({id:'pages.hotfix.no', defaultMessage:'No'})
          return returnval
        }
      }
    },
    {
      title: <FormattedMessage id="pages.hotfix.operation" defaultMessage="Operating" />,
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record)}
              style={{
                marginRight: 8,
              }}
            >
              {intl.formatMessage({id:'pages.hotfix.save', defaultMessage:"Save"})}
            </Typography.Link>
            <Popconfirm title={intl.formatMessage({id:'pages.hotfix.confirm.cancel', defaultMessage:"Are you sure to cancel?"})}
             onConfirm={cancel}>
              <a>{intl.formatMessage({id:'pages.hotfix.cancel', defaultMessage:"Cancel"})}</a>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)} style={{
                marginRight: 8,
              }}>
              {intl.formatMessage({id:'pages.hotfix.edit', defaultMessage:"Edit"})}
            </Typography.Link>
            <Popconfirm title={intl.formatMessage({id:'pages.hotfix.confirm.delete_kernelversion', defaultMessage:'Are you sure to delete this kernel version?'})} 
            onConfirm={async () => {
              if (record.id == undefined) {
                message.error(intl.formatMessage({
                      id: 'pages.hotfix.delete_hotfix_not_exist',
                      defaultMessage: "Not allow to delete this hotfix"
                }))
                console.log(intl.formatMessage({
                    id: 'pages.hotfix.delete_hotfix_not_exist',
                    defaultMessage: "Not allow to delete this hotfix"
                }))
              } else {
                  await handleDelKernelVersion(record, intl);
                  versionlistRef.current.reload();
              }
            }}>
              <a><FormattedMessage id="pages.hotfix.delete" defaultMessage="hotfix delete" /></a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.valueType,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <>
      <VersionConfigForm data={props.OSTypedata} onSuccess={onPostTask} />
      <Divider />
      <Form form={form} component={false}>
        <ProTable
          headerTitle={intl.formatMessage({
            id: 'pages.hotfix.title.versionconf',
            defaultMessage: 'kernel verion conf',
          })}
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          rowClassName="editable-row"
          search={false}
          actionRef={versionlistRef}
          rowKey="id"
          toolBarRender={() => [
          ]}
          request={getKernelVersionList}
          // columns={columns}
          columns={mergedColumns}
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
    </>
  );
});
export default VersionConfigList;